package drugdealer.control;

import java.io.IOException;
import java.sql.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import drugdealer.data.MedicoDAO;
import drugdealer.exception.UserTypeException;
import drugdealer.model.Medico;

/**
 * Servlet implementation class CadastraServlet.
 * 
 * When a new user registers her/himself to the system this servlet
 * manages database update with the user's data. 
 * 
 * @author dave
 */
@WebServlet("/cadastroMedico")
@SuppressWarnings("serial")
public class CadastroMedicoServlet extends HttpServlet {

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CadastroMedicoServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("CadastroServlet.doPost()");
		
		String nome = (String) request.getParameter("nome");
		String email = (String) request.getParameter("email");
		String rg = (String) request.getParameter("rg");
		String endereco = (String) request.getParameter("endereco");
		String senha = (String) request.getParameter("senha");
		String crm = (String) request.getParameter("crm");
		
		// Data format is yyyy-mm-dd
		Date data = java.sql.Date.valueOf(request.getParameter("data"));

		String url = "";

		Medico m = new Medico();

		m.setNome(nome);
		m.setEmail(email);
		m.setRG(rg);
		m.setEndereco(endereco);
		m.setSenha(senha);
		m.setCRM(crm);
		m.setAniversario(data);
		
		int success = 0;

		try {
			success = MedicoDAO.insert(m);
		} catch (UserTypeException e) {
			System.out.println("CadastroServlet.doPost(): Requested user type doesn't exist!"
					+ " => user.getClass(): " + m.getClass());
			e.printStackTrace();
		}
		
		if (success != 0) {
			System.out.println("\tMedic registration successful");
			url = "/seguranca/administrador/medicoRegSucesso.jsp";
		} else {
			System.out.println("\tMedic registration failed");
			url = "/seguranca/administrador/index.jsp";
		}
		
		
		response.sendRedirect(url);
	}
}
